﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Net.Mime;

namespace TakeNote
{
    class Server
    {
        static int m_nEuckrCodepage = 51949;
        static System.Text.Encoding m_EUC_KR = System.Text.Encoding.GetEncoding(m_nEuckrCodepage);

        public MainWindow WindowMain;
        public Window1 window1 = null;

        private Thread m_ThreadListen = null;
        private TcpListener m_TcpListener = null;

        private Socket m_SocketServer = null;
        private Socket m_SocketServerFile = null;


        private static Thread m_ThreadReceive = null;

        private string m_sServerIP;
        private int m_nServerPort;     


        public string ServerIP
        {
            get { return m_sServerIP; }
            set { m_sServerIP = value; }
        }

        public int ServerPort
        {
            get { return m_nServerPort; }
            set { m_nServerPort = value; }
        }
        public Server()
        {
        }

        public List<string> FileName = new List<string>();
        public List<int> FileSize = new List<int>();
        public List<string> underPathFiles = new List<string>();


        public void StartSocket()
        {
            try
            { 
                m_ThreadListen = new Thread(new ThreadStart(Listen));
                m_ThreadListen.Start();
                m_ThreadListen.IsBackground = true;
                WindowMain.SetText("서버가 시작되었습니다.\r\n");
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
        }

        private void Listen()
        {           
            try
            {
                IPAddress ipAddress = IPAddress.Parse(m_sServerIP);   
                IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, m_nServerPort);

                m_TcpListener = new TcpListener(ipEndPoint);
                m_TcpListener.Start();  //새객체를 대기 상태로 변환        //1. Start()  2. AcceptSocket();
                m_SocketServer = m_TcpListener.AcceptSocket();               
                
                System.Windows.MessageBox.Show("연결이 감지되었습니다.");
                
                WindowMain.FileOpenButtonIsEnabled(true);

                //m_ThreadReceive = new Thread(new ThreadStart(ReceiveData)); //데이터 받기
                //m_ThreadReceive.Start();
                //m_ThreadReceive.IsBackground = true;


                ////UDP
                //byte[] data = new byte[4096];

                //newsock = new UdpClient(ipEndPoint);
                //IPEndPoint sender  = new IPEndPoint(IPAddress.Any, m_nServerPort); //클라이언트의 IP주소를 저장
                //data = newsock.Receive(ref sender);
                //newsock.Send(data, data.Length, sender);

                //System.Diagnostics.Debug.WriteLine("message received from {0} : " ,sender.ToString());
                //System.Diagnostics.Debug.WriteLine(Encoding.ASCII.GetString(data,0,data.Length));               
                //while (true)
                //{
                //    data = newsock.Receive(ref sender);
                //    System.Diagnostics.Debug.WriteLine(Encoding.ASCII.GetString(data,0,data.Length));
                //   // newsock.Send(data,data.Length,sender);
                //}
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
        }

        public void DoRunning()  //전송 쓰래드
        {
            Thread[] aThread = { new Thread(new ThreadStart(SendFile)) };
            foreach (Thread t in aThread)
            {
                t.Start();
            }
        }

        private void SendFile()   //파일 전송
        {
            try
            {
                List<string> sFileNames = new List<string>();
                for (int i = 0; i < FileName.Count; i++)
                {
                    sFileNames.Add(FileName[i]);
                    int nStartIndex = 0;
                    int nSendSize = 512;
                    int nSendDataLength = 0;

                    string[] sFileName = sFileNames[i].Split('\\');
                    string sendData = "FILE" + ":" + sFileName[sFileName.Length - 1] + ":" + FileSize[i];
                    byte[] bSendData = m_EUC_KR.GetBytes(sendData);

                    nSendDataLength = m_SocketServer.Send(bSendData); //소켓을통해 Send

                    //WindowMain.FileOpenButtonIsEnabled(false);

                    Thread.Sleep(500);
                    byte[] bFileData = new byte[FileSize[i]];

                    FileStream fs = File.Open(sFileNames[i], FileMode.OpenOrCreate);
                    fs.Read(bFileData, 0, FileSize[i]);
                    fs.Close();

                    Thread.Sleep(500);
                    while (nStartIndex < FileSize[i])
                    {
                        if (nStartIndex + nSendSize > FileSize[i])
                        {
                            nSendSize = FileSize[i] - nStartIndex;
                        }
                       
                        nSendDataLength = m_SocketServer.Send(bFileData, nStartIndex, nSendSize, SocketFlags.None);
                        nStartIndex += nSendDataLength;
                    
                    }

                    Thread.Sleep(1000);
                    // WindowMain.FileOpenButtonIsEnabled(true);
                }
                FileName.Clear();
                FileSize.Clear();
            }

            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
        }

        public void StopSocket()
        {
            try
            {
                if (m_SocketServer != null)
                {
                    m_SocketServer.Close();
                    m_SocketServer = null;
                }

                if (m_SocketServerFile != null)
                {
                    m_SocketServerFile.Close();
                    m_SocketServerFile = null;
                }

                if (m_TcpListener != null)
                {
                    m_TcpListener.Stop();
                    m_TcpListener = null;
                }

                if (m_ThreadReceive != null)
                {
                    m_ThreadReceive.Abort();
                    m_ThreadReceive = null;
                }

                WindowMain.SetText("서버가 중지되었습니다.\r\n");
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
        }

        public void CloseSocket()
        {
            try
            {
                if (m_SocketServer != null)
                {
                    m_SocketServer.Close();
                }

                if (m_ThreadListen != null)
                {
                    m_ThreadListen.Abort();
                }

                if (m_SocketServerFile != null)
                {
                    m_SocketServerFile.Close();
                }

                if (m_TcpListener != null)
                {
                    m_TcpListener.Stop();
                }

            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
        }
    }
}